﻿using IOP.Extension.Convert;
using System;

namespace IOP.Protocols.MQTT.Package
{
    /// <summary>
    /// 发布回执包
    /// </summary>
    public struct PubackPackage : IMQTTPackage
    {
        /// <summary>
        /// 报文类型
        /// </summary>
        public ControlPacketType PacketType { get => ControlPacketType.PUBACK; }
        /// <summary>
        /// 剩余长度
        /// </summary>
        public uint RemainingLength { get => 2; }

        /// <summary>
        /// 报文标识符
        /// </summary>
        public ushort PacketIdentifier;

        /// <summary>
        /// 构造函数
        /// </summary>
        public PubackPackage(ushort packetId)
        {
            PacketIdentifier = packetId;
        }

        /// <summary>
        /// 转换为字节码
        /// </summary>
        /// <returns></returns>
        public Span<byte> ToBytes()
        {
            Span<byte> bytes = stackalloc byte[4];
            Span<byte> result = new byte[4];
            int index = 0;
            bytes[index++] = (byte)((byte)PacketType << 4);
            bytes[index++] = (byte)RemainingLength;
            PacketIdentifier.WriteBytes(ref bytes, ref index);
            bytes.TryCopyTo(result);
            return result;
        }
    }
}
